#    Copyright 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import application, cis, command, compatibleunit, geography, oms, staker, symbology, unsorted
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
import _mysql as mysql

#VegetationManager is being created as an integrated but slightly separated set of models 
#From the GIS, all Model Names and such are prepended with VegetationManager
class VegetationManagerJob(models.Model):
    """VegetationManagerJob is the Main Job Listing for Right of Way Management"""
    Description=models.TextField()
    VegetationManagerCrew=models.ForeignKey('VegetationManagerCrew', null=True, blank=True)
    WorkStartDate=models.DateField(null=True, blank=True)
    WorkEndDate=models.DateField(null=True, blank=True)
    CreateDate=models.DateField(null=True, blank=True)
    VegetationManagerJobStatus=models.ForeignKey('VegetationManagerJobStatus')
    HoursWorkedQuantity=models.FloatField(null=True, blank=True)
    WidthInFeet=models.IntegerField(null=True, blank=True)  #Default width in feet, can be overridden at the VegetationManagerJobSpan Level
    ActiveIndicator=models.NullBooleanField(null=True, blank=True)
    CreateCommand=models.ForeignKey('Command', null=True, blank=True)
    StakerWorkOrder=models.ForeignKey('StakerWorkOrder', null=True, blank=True)
    SubstationName=models.CharField(max_length=250, null=True, blank=True)
    CircuitName=models.CharField(max_length=250, null=True, blank=True)
    TrimRightOfWayIndicator=models.NullBooleanField(null=True, blank=True)
    ResidesOnServerIndicator=models.BooleanField()
    objects=models.GeoManager()
    class Meta:
        db_table=u'vegetationmanagerjob'
        app_label='djangoproject'
    def GetIndexWhenReverseSorted(self):
        VegetationManagerJobs=VegetationManagerJob.objects.all().order_by('-id')
        i = 0
        while(True):
            if(VegetationManagerJobs[i] == self):
                return i
            i = i + 1
    def CalculateTotalFeet(self):
        VegetationManagerJobSpans=VegetationManagerJobSpan.objects.filter(VegetationManagerJob=self)
        Total=0.0
        for vegetationManagerJobSpan in VegetationManagerJobSpans:
            Total=Total + vegetationManagerJobSpan.Line.length
        return Total
    
class VegetationManagerJobStatus(models.Model):
    """VegetationManagerJobStatus is possible states for a job (In Progress, Completed, etc)"""
    Name=models.CharField(unique=True, max_length=250)
    Description=models.TextField(null=True, blank=True)
    ResidesOnServerIndicator=models.BooleanField()
    CreateCommand=models.ForeignKey('Command', null=True, blank=True)
    objects=models.GeoManager()
    def __unicode__(self):
        return self.Name
    class Meta:
        db_table=u'vegetationmanagerjobstatus'
        app_label='djangoproject'
    def GetIndexWhenReverseSorted(self):
        VegetationManagerJobStatuses=VegetationManagerJobStatus.objects.all().order_by('-id')
        i = 0
        while(True):
            if(VegetationManagerJobStatuses[i] == self):
                return i
            i = i + 1

class VegetationManagerCrew(models.Model):
    WorkerQuantity=models.IntegerField(null=True, blank=True)
    Company=models.ForeignKey('Company')
    WorkStartDate=models.DateField(null=True, blank=True)
    WorkEndDate=models.DateField(null=True, blank=True)
    ActiveIndicator=models.NullBooleanField(null=True, blank=True)
    RadioNumber=models.CharField(max_length=250, null=True, blank=True)
    ResidesOnServerIndicator=models.BooleanField()
    CreateCommand=models.ForeignKey('Command', null=True, blank=True)
    objects=models.GeoManager()    
    class Meta:
        db_table=u'vegetationmanagercrew'
        app_label='djangoproject'
    def GetIndexWhenReverseSorted(self):
        VegetationManagerCrews=VegetationManagerCrew.objects.all().order_by('-id')
        i = 0
        while(True):
            if(VegetationManagerCrews[i] == self):
                return i
            i = i + 1


class VegetationManagerJobSpan(models.Model):
    """VegetationManagerJobSpan holds the the lines that are included with a vegetation manager job)"""
    VegetationManagerJob=models.ForeignKey('VegetationManagerJob')
    Line=models.LineStringField(db_column='the_geom', srid=djangoproject.settings.COOPGISSRID)
    Spanid=models.IntegerField()  #Changes to Spans do not affect VegetationManagerGeography so no Foreign Key relation
    WidthInFeet=models.FloatField(null=True, blank=True)
    WorkCompletedDate=models.DateField(null=True, blank=True)
    SymbologyJobYear=models.CharField(null=True, blank=True, max_length=250, db_column='symbologyjobyear')
    SymbologyCrew=models.CharField(null=True, blank=True, max_length=250, db_column='symbologycrew')
    CreateCommand=models.ForeignKey('Command', null=True, blank=True)
    ResidesOnServerIndicator=models.BooleanField()
    objects=models.GeoManager()
    def CalculateSymbologyFields(self):
        try:
            self.SymbologyJobYear=str(self.VegetationManagerJob.StartDate.year)
        except:
            self.SymbologyJobYear=str(datetime.datetime.now().year)
        try:
            self.SymbologyCrew=str(self.VegetationManagerJob.VegetationManagerCrew.id)
        except:
            self.SymbologyCrew='0'
        self.save()
    class Meta:
        db_table=u'vegetationmanagerjobspan'
        app_label='djangoproject'

